import React, { useRef, useState, useEffect } from 'react'
import styles from './index.module.less'
import MarkdownIt from 'markdown-it'
import MdEditor from 'react-markdown-editor-lite'
import { Button } from 'antd'
import BackHomeBtn from '../../components/backHome'
import 'react-markdown-editor-lite/lib/index.css'

const mdParser = new MarkdownIt(/* Markdown-it options */)

const Interview = () => {
	// const { interview } = useStores()

	const edit = useRef()
	const editRef = useRef()

	const [editorTextValue, setEditorTextValue] = useState()
	const [editorHtmlValue, setEditorHtmlValue] = useState()

	const handleEditorChange = ({ html, text }) => {
		setEditorTextValue(() => text)
		setEditorHtmlValue(() => html)
	}

	const handleImageUpload = (file, callback) => {
		const reader = new FileReader()
		reader.onload = () => {
			// const convertBase64UrlToBlob = (urlData) => {
			//     let arr = urlData.split(','), mime = arr[0].match(/:(.*?)/)[1]
			//     let bstr = atob(arr[1])
			//     let n = bstr.length
			//     let u8arr = new Uint8Array(n)
			//     while (n--) {
			//         u8arr[n] = bstr.charCodeAt(n)
			//     }
			//     return new Blob([u8arr], {type:mime})
			// }
			// const blob = convertBase64UrlToBlob(reader.result)
			setTimeout(() => {
				// setTimeout 模拟异步上传图片
				// 当异步上传获取图片地址后，执行calback回调（参数为imageUrl字符串），即可将图片地址写入markdown
				callback(reader.result)
			}, 1000)
		}
		reader.readAsDataURL(file)
	}

	useEffect(() => {
		// 设置a标签 打开新窗口
		if (editRef && editRef.current) {
			const links = editRef.current.getElementsByTagName('a')
			if (links && links.length > 0) {
				const linksArr = Array.from(links)
				linksArr.every((a) => {
					a.target = '_blank'
					return null
				})
			}
		}
	}, [editorTextValue, editRef])

	useEffect(() => {
		if (edit && edit.current) {
			// 初始化 双屏显示
			edit.current.setView({
				html: false,
				menu: true,
				md: true,
			})
		}
	}, [edit])

	const release = () => {
		console.log(editorHtmlValue)
		console.log(editorTextValue)
	}

	return (
		<div className={'mdEdit'} ref={editRef}>
			<div className={styles.btnBox}>
				<BackHomeBtn />
				<Button onClick={release} type={'primary'}>
					发布
				</Button>
			</div>
			<MdEditor
				ref={edit}
				value={editorTextValue}
				style={{ height: '300px' }}
				renderHTML={(text) => mdParser.render(text)}
				onChange={handleEditorChange}
				onImageUpload={handleImageUpload}
			/>
		</div>
	)
}

export default Interview
